<?php

namespace App\Admin\Controllers;

use App\Dengje\Utils\Settings;
use Dcat\Admin\Http\Controllers\AdminController;
use Dcat\Admin\Layout\Content;
use Dcat\Admin\Layout\Row;
use Illuminate\Http\Request;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\DB;
use ZipArchive;

class UpdateController extends AdminController
{

    public function index(Content $content)
    {

        $version = Settings::get('version');
        return $content
            ->header('在线更新')
            ->description('')
            ->body(view('admin/update/index', compact('version')));

    }

    public function check(Request $request)
    {

        // 授权检测
        $authcode = env('AUTHCODE');
        $query = @file_get_contents('https://auth.supengjun.com/check.php?url=' . $_SERVER['HTTP_HOST'] . '&authcode=' . $authcode);
        if ($query = json_decode($query, true)) {
            if ($query['code'] != 1) {
                return [
                    'msg' => '授权码不正确',
                    'code' => 400,
                ];
            }
        }

        $content = json_decode(file_get_contents('http://update.supengjun.com/da-upver/1287c616b844f48d3ef99941685ec5cd'), true);
        $version = Settings::get('version');
        $version2 = $content['version'];
//        var_dump($content->version);exit();
        $isNew = $this->versionPra($version, $version2);
        if ($isNew) {
            return [
                'msg' => $content['msg'],
                'version' => $content['version'],
                'code' => 200,
            ];
        }
        return [
            'msg' => '没有新的版本',
            'code' => 100,
        ];
    }


    /**
     * 下载文件
     * @param $url
     * @param $path
     */
    public function downloadFile()
    {
        // 判断版本
        $content = json_decode(file_get_contents('http://update.supengjun.com/da-upver/1287c616b844f48d3ef99941685ec5cd'), true);
        $version = Settings::get('version');
        $version2 = $content['version'];
        $isNew = $this->versionPra($version, $version2);
        if (!$isNew) {
            return false;
        }
        //缓存版本
        cache(['temp_version' => $version2], now()->addMinutes(20));

        $content = json_decode(file_get_contents('http://update.supengjun.com/da-upver/1287c616b844f48d3ef99941685ec5cd'));
        file_put_contents(public_path('update/update.zip'), file_get_contents($content->download_url));
        return true;
    }

    /**
     * 解压文件
     * @return \Illuminate\Cache\CacheManager|\Illuminate\Contracts\Foundation\Application|\Illuminate\Foundation\Application|mixed|object|\think\App
     * @throws \Exception
     */
    public function unzip()
    {
        $newfile = public_path('update/update.zip', ZIPARCHIVE::OVERWRITE);
        $zip = new ZipArchive();

        if ($zip->open($newfile) == true) {
            $zip->extractTo(base_path());//假设解压缩到在当前路径下images文件夹的子文件夹php
            $zip->close();//关闭处理的zip文件

        }
        return true;
    }

    /**
     * 更新数据库
     */
    public function updateSql()
    {

        // 判断有没有要更新的数据库
        if (file_exists(database_path('update.sql'))) {
            $this->runSql();
        }

        // 更新版本号
        $temp_version = cache('temp_version');
        Settings::set('version', $temp_version);
    }

    private function runSql()
    {
        $sqlPath = database_path('update.sql');
        $sqlContent = file_get_contents($sqlPath);


        try {

            $db = DB::reconnect('mysql');
            $db->getPdo()->exec($sqlContent);
        } catch (\Exception $exception) {
            return $exception;
        }
    }

    /**
     * @param $version
     * @param $version2
     * @return bool
     */
    private function versionPra($version, $version2)
    {

        $version = explode('.', $version);
        $version = implode('', $version);
        $version2 = explode('.', $version2);
        $version2 = implode('', $version2);
        if (strlen($version) >= strlen($version2)) {
            $version2 = str_pad($version2, strlen($version), "0", STR_PAD_RIGHT);
        } else {
            $version = str_pad($version, strlen($version2), "0", STR_PAD_RIGHT);
        }
        if ($version2 > $version) {
            return true;
        } elseif ($version2 == $version) {
            return false;
        } else {
            return false;
        }

    }

}
